<template>
  <el-col :span="Number(item.span || 24)">
    <el-form-item :style="item.formStyle ? JSON.parse(item.formStyle) : '{}'" :label="item.label ? item.label + ':' : ''" :rules="item.hide || !item.hasrules ? null : item.rules ? item.rules : [{ required: true, message: `请输入${item.label}`, trigger: 'blur' }].concat(item.otherRules ? item.otherRules : [])" :prop="itemKey" v-show="!item.hide">
      <div v-if="item.tip" class="formItemTip">{{ item.tip }}</div>
      <el-input v-if="item.type == 'input'" @input="changeRadio" :show-word-limit="item.showWordLimit" :maxlength="item.maxlength ?? 100" :rows="item.rows || 5" :autosize="item.autosize" :disabled="item.disabled" :type="item.otherType || item.type" v-model="itemValuex" :show-password="item.showPassword" :clearable="true" :placeholder="item.placeholder ?? `请输入${item.label}`" />
      <el-select v-else-if="item.type == 'select'" v-model="itemValuex" @change="changeRadio" :style="item.style" :multiple="item.multiple" :clearable="true" :disabled="item.disabled" :placeholder="item.placeholder || `请选择${item.label}`" :allowCreate="item.allowCreate" :loading="remoting" :remote-method="(e: any) => remoteMethod({ e, item })" :remote-show-suffix="item.remote" :reserve-keyword="item.remote" :remote="item.remote" :filterable="item.remote" :defaultFirstOption="item.defaultFirstOption">
        <el-option v-for="s in item.values" :key="item.nolabel ? s : s[item.aid || 'id']" :label="item.nolabel ? s : s[item.name || 'name']" :value="item.nolabel ? s : s[item.aid || 'id']"> </el-option>
      </el-select>
      <el-checkbox-group v-else-if="item.type == 'checkbox'" @change="changeRadio" :disabled="item.disabled" v-model="itemValuex">
        <el-checkbox-button :label="item.nolabel ? c : c[item.aid || 'id']" v-for="(c, i) in item.values" :key="`CHECK_${i}`">
          {{ item.nolabel ? c : c[item.name || "name"] }}
        </el-checkbox-button>
      </el-checkbox-group>
      <el-radio-group v-else-if="item.type == 'radio'" v-model="itemValuex" :disabled="item.disabled">
        <el-radio-button :label="item.nolabel ? r : r[item.aid || 'id']" v-for="(r, i) in item.values" :key="'r' + i">
          {{ item.nolabel ? r : r[item.name || "name"] }}
        </el-radio-button>
      </el-radio-group>
      <el-date-picker v-else-if="item.type == 'daterange' || item.type == 'datetimerange' || item.type == 'monthrange' || item.type == 'date' || item.type == 'datetime'" v-model="itemValuex" :type="item.type" :default-time="item.defaultTime" :clearable="true" :value-format="item.format" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="item.shortcuts || shortcuts" placeholder="请选择时间"> </el-date-picker>
      <el-time-picker v-else-if="item.type == 'time_picker'" :placeholder="item.placeholder ?? `请选择${item.label}`" v-model="itemValuex" :is-range="item.is_range" range-separator="至" start-placeholder="开始时间" :value-format="item.value_format || 'HH:mm'" end-placeholder="结束时间" :format="item.format || 'HH:mm'" />
      <el-time-select v-else-if="item.type == 'time'" v-model="itemValuex" :start="item.start" :end="item.end" :placeholder="item.placeholder ?? `请输入${item.label}`"> </el-time-select>
      <el-cascader v-else-if="item.type == 'cascader'" :props="item.props" :style="item.style" :options="item.options" v-model="itemValuex" placeholder="请选择" :clearable="true"></el-cascader>
      <Ceditor v-else-if="item.type == 'editor'" :editorProp="itemKey" ref="editorRef" :text="itemValuex" @getEditorValue="getEditorValue"></Ceditor>
      <CuploadFile v-else-if="fileType.includes(item.type as CuploadFileTypesType)" @beforeUpload="beforeUpload" :item="item" ref="cuploadFileRef" :fileProp="itemKey" @getFile="getFile" :type="item.type" />
      <div v-else-if="item.type == 'text'">{{ itemValuex }}</div>
      <img width="120" v-else-if="item.type == 'img'" :src="itemValuex" alt="" />
      <slot name="otherItem" :item="item" :key="itemKey"></slot>
    </el-form-item>
  </el-col>
</template>
<script setup lang="ts">
import { fileType } from "./form";
import { formEmit } from "@/components/Cform/form";
import type { UploadRawFile } from "element-plus";
import { parseTime } from "@/assets/utils";
const props = defineProps(["item", "itemValue", "itemKey", "type", "form", "id"]);
const emit = defineEmits(formEmit);

const itemValuex = ref("");
watch(
  () => props.itemValue,
  () => {
    itemValuex.value = props.itemValue;
  },
  { immediate: true }
);

const cuploadFileRef = ref<CuploadFileType>();
const editorRef = ref();
const shortcuts = ref([
  { text: "已过期", value: [parseTime(new Date().getTime()), parseTime(new Date().getTime())] },
  { text: "近5天", value: [parseTime(new Date().getTime()), parseTime(new Date().getTime() + 3600 * 1000 * 24 * 5)] },
  { text: "近15天", value: [parseTime(new Date().getTime()), parseTime(new Date().getTime() + 3600 * 1000 * 24 * 15)] }
]);
const remoting = ref(false);
const remoteMethod = async ({ e, item }: { e: any; item: any }) => {
  remoting.value = true;
  let url = item.url + e;
  let res = await hfoRequest.get({ url: url, params: { ...item?.params } });
  if (res) {
    emit("changeProps", { e: res.data.content, propsName: ["cformOpt", "items", props.itemKey, "values"] });
    remoting.value = false;
  }
};
const getFile = ({ e }: { e: any }) => {
  if (props.item.otherGetFile) return emit("otherGetFileFn", { e, props });
  if (props.item.type === "uImg") return emit("changeRadio", {key:props.itemKey, e});
  let list = e.map((ite: any) => {
    return ite.name ? { url: ite.response.data[0] } : ite;
  });
  emit("changeRadio", {key:props.itemKey,e: JSON.stringify(list)});
};
const refreshItems = async () => {
  let item = props.item;
  if ((item.type !== "radio" && item.type !== "select") || !item.url) return;
  let res = await hfoRequest.get({ url: item.url, params: item.params });
  if (!res) return;
  let arr = [];
  if (item.valueType == "Object") {
    for (var k in res.data) {
      arr.push({ label: k, text: res.data[k] });
    }
  } else {
    arr = arr.concat(res.data.content);
  }
  if (item.values) arr = [item.values, ...arr];
  emit("changeProps", { e: arr, propsName: ["cformOpt", "items", props.itemKey, "values"] });
};
const initFormRef = (data: any) => {
  let formType = ["radio", "checkbox", "select", "cascader", "daterange", "editor", ...fileType];
  let item = props.item;
  if (item.hide) return;
  if (formType.indexOf(item.type) == -1) return emit("changeRadio", {key:props.itemKey, e:data});
  if (fileType.includes(item.type as CuploadFileTypesType)) return initFile(data);
  if (item.type == "select" && data) return emit("changeRadio", {key:props.itemKey, e:item.multiple ? ref(data.constructor == Array ? data : data.includes("[") && data.includes("]") ? JSON.parse(data) : data.split(",")) : ref(data + "")});
  if (item.type == "editor") return editorRef.value.setVal(data || "");
  emit("changeRadio", {key:props.itemKey, e:data});
};
const initFile = (e: any) => {
  if(props.item.otherGetFile)return
  if (props.item.type === "uImg") {
    cuploadFileRef.value.fileUrl = e
    emit("changeRadio", {key:props.itemKey, e:e});
  } else {
    cuploadFileRef.value.fileList = e.constructor == Array ? e : JSON.parse(e)
    emit("changeRadio", {key:props.itemKey, e:e.constructor == Array ? e : JSON.parse(e)})
  }
};
const changeRadio = (e) => {
  emit("changeRadio", { e, id: props.id, key: props.itemKey, item: props.item });
};
const beforeUpload = ({ file }: { file: UploadRawFile }) => {
  emit("beforeUpload", { file, item: props.item, itemKey: props.itemKey });
};
const getEditorValue = (e: string) => {
  emit("changeRadio",{ key:props.itemKey, e});
};
refreshItems();
defineExpose({
  initFormRef,
  itemKey: props.itemKey
});
</script>
<style lang="scss" scoped></style>
